package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import no.doomsday.scripting.simplescriptengine.ScriptEngine;
	
	/**
	 * ...
	 * @author Andreas Rønning (andreas@doomsday.no)
	 */
	public class Main extends Sprite 
	{
		private var delayTimer:Timer;
		private var _totalScore:Number = 0;
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			ScriptEngine.initialize();
			ScriptEngine.mapCommand("beginFill", graphics.beginFill);
			ScriptEngine.mapCommand("drawRect", graphics.drawRect);
			ScriptEngine.mapCommand("clearStageGraphics", graphics.clear);
			ScriptEngine.mapCommand("question", question);
			ScriptEngine.mapCommand("setTotalScore", setTotalScore);
			ScriptEngine.mapCommand("getTotalScore", getTotalScore);
			ScriptEngine.expose(this);
			ScriptEngine.loadAndRun("test.script");
			
			delayTimer = new Timer(1000, 1);
			delayTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
		}
		private function drawBox(x:Number,y:Number,width:Number,height:Number):void
		{
			graphics.clear();
			graphics.beginFill(0xFF00000);
			graphics.drawRect(x, y, width, height);
		}
		private function question(q:String):int {
			trace("Question: " + q);
			delayTimer.reset();
			delayTimer.start();
			_totalScore += Math.random()*5;
		}
		
		private function onTimerComplete(e:TimerEvent):void 
		{
			ScriptEngine.resume();
		}
		public function setTotalScore(n:Number):void {
			_totalScore = n;
		}
		public function getTotalScore():Number { return _totalScore; }
		
	}
	
}